package com.david.common.utils;

import com.david.common.constant.SecurityConstants;
import io.jsonwebtoken.Claims;


import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.xml.bind.DatatypeConverter;
import java.util.Date;
import java.util.Map;

@RequiredArgsConstructor
@Component
@Slf4j
public class JwtUtils {
    private  static final byte[] secretKey = DatatypeConverter.parseBase64Binary(SecurityConstants.JWT_SECRET_KEY);
    public String generateJwt(Map<String,Object> claims) {
        // TODO 与Demo中相比设置少很多
        log.info("claims:{}",claims);
        JwtBuilder jwtBuilder = Jwts.builder().setClaims(claims).signWith(Keys.hmacShaKeyFor(secretKey)).setExpiration(new Date(System.currentTimeMillis() + SecurityConstants.TOKEN_EXPIRATION_TIME * 1000));
        String compact = jwtBuilder.compact();
        System.out.println("-------------Jwt生成:"+compact+"-----------");
        return compact;
    }
// refreshToken是给“记住我”功能使用的
//    public String getRefrshToken(String username) {
//        log.info("----------生成refreshToken----------");
//        return Jwts.builder().signWith(Keys.hmacShaKeyFor(secretKey)).setSubject(username).setExpiration()
//    }
    public Claims parseJwt(String jwt) {
        return Jwts.parserBuilder()
                .setSigningKey(Keys.hmacShaKeyFor(secretKey))
                .build()
                .parseClaimsJws(jwt)
                .getBody();
    }
}
